package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-master/cache"
	"post-master/model"
	"strconv"
	"time"
)

func Detail(c *gin.Context) {
	id := c.Query("id")

	var master model.Master
	redis_key := "master_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).First(&master)
		jsonData, _ := json.Marshal(master)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &master)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": master,
	})

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))

	var count int64
	model.DB.Model(&model.Master{}).Count(&count)

	offset := (page - 1) * size
	var master []model.Master

	redis_key := "master_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&master)
		jsonData, _ := json.Marshal(master)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &master)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count":  count,
			"master": master,
		},
	})

}

func Collection(c *gin.Context) {
	user_id, _ := strconv.Atoi(c.PostForm("user_id"))
	master_id, _ := strconv.Atoi(c.PostForm("master_id"))

	var collection model.Collection
	err := model.DB.Where("user_id = ? and master_id = ?", user_id, master_id).First(&collection).Error
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复收藏",
		})
		return
	}

	collection = model.Collection{
		UserID:   uint(user_id),
		MasterID: uint(master_id),
	}

	err = model.DB.Create(&collection).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏记录添加失败",
			"err":  err.Error(),
		})
		return
	}

	var master model.Master
	err = model.DB.Where("id = ?", master_id).First(&master).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不存在",
		})
		return
	}

	master.CollectionCount++
	err = model.DB.Save(&master).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏量添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
	return

}
